package com.heima.wemedia.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.wemedia.dtos.WmNewsDto;
import com.heima.model.wemedia.dtos.WmNewsPageReqDto;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNews;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmNewsService;
import com.heima.wemedia.thread.WmUserThreadLocal;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
@Transactional
public class WmNewsServiceImpl extends ServiceImpl<WmNewsMapper, WmNews> implements WmNewsService {
	@Autowired
	private WmNewsMapper wmNewsMapper;
	@Autowired
	private WmMaterialMapper wmMaterialMapper;
	@Autowired
	private WmNewsMaterialMapper wmNewsMaterialMapper;
	
	@Autowired
	private KafkaTemplate<String, String> kafkaTemplate;
	
	@Override
	public ResponseResult downOrUp(WmNewsDto dto) {
		Integer id = dto.getId();
		
		//查询新闻
		WmNews wmNews = wmNewsMapper.selectById(id);
		if (wmNews == null) {
			return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST, "新闻不存在");
		}
		
		//检测新闻是否发布
		Short status = wmNews.getStatus();
		if (status != 9) {
			return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "当前文章不是发布装填,不能上架");
		}
		//获取到dto中新闻状态,写入到对象中进行更改.
		wmNews.setEnable(dto.getEnable());
		
		int updateResult = wmNewsMapper.updateById(wmNews);
		if (updateResult < 1) {
			return ResponseResult.errorResult(AppHttpCodeEnum.SERVER_ERROR, "修改文章失败");
		}
		
		//将消息发送到article
		kafkaTemplate.send("news.down.up.topic", JSON.toJSONString(wmNews));
		return ResponseResult.okResult("");
	}
	
	@Override
	@Transactional(rollbackFor = RuntimeException.class)
	public ResponseResult submit(WmNewsDto dto) {
		//提取新闻内容
		WmNews wmNews = wmNewsDot2WmNews(dto);
		if (wmNews == null) {
			return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
		}
		
		//插入新闻列表
		int insert = wmNewsMapper.insert(wmNews);
		if (insert < 1) {
			return ResponseResult.errorResult(AppHttpCodeEnum.LOGIN_PASSWORD_ERROR);
		}
		
		//判断是不是草稿
		Short status = dto.getStatus();
		if (status == 0) {
			return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
		}
		
		//提取新闻图片
		String content = dto.getContent();
		List<String> contenImages = getContenImages(content);
		
		
		
		
		//如果是自动布局,要到内容图中提取图片作为封面图
		List<String> images = dto.getImages();
		Short type = dto.getType();
		List<String> coverImages = getCoverImages(type, images, contenImages);
		//素材添加
		Boolean aBoolean = addMaterial(wmNews.getId(), contenImages, 0);
		if (aBoolean == false) {
			throw new RuntimeException("内容添加失败");
		}
		Boolean aBoolean1 = addMaterial(wmNews.getId(), coverImages, 1);
		if (aBoolean1 == false) {
			throw new RuntimeException("封面添加失败");
		}
		
		//素材和新闻关系添加
		return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
	}
	//素材添加
	@Transactional(rollbackFor = RuntimeException.class)
	public Boolean addMaterial(Integer newsId, List<String> images, Integer type) {
		if (CollectionUtils.isEmpty(images)) {
			return true;
		}
		for (String url : images) {
			if (StringUtils.isEmpty(url)) {
				continue;
			}
			WmMaterial material = new WmMaterial();
			material.setUserId(WmUserThreadLocal.get().getId());
			material.setUrl(url);
			material.setType((short) 0);
			material.setIsCollection((short) 0);
			material.setCreatedTime(new Date());
			int insert = wmMaterialMapper.insert(material);
			if (insert < 1) {
				throw new RuntimeException("素材添加失败");
			}
			
			WmNewsMaterial newsMaterial = new WmNewsMaterial();
			newsMaterial.setType(type.shortValue());
			newsMaterial.setOrd((short) 1);
			newsMaterial.setNewsId(newsId);
			newsMaterial.setMaterialId(material.getId());
			int insert1 = wmNewsMaterialMapper.insert(newsMaterial);
			if (insert1 < 1) {
				throw new RuntimeException("素材关系添加失败");
			}
		}
		return true;
		
	}
	
	private List<String> getCoverImages(Short type, List<String> images, List<String> contentImages) {
		if (type == -1) {
			if (contentImages.size() >= 3) {
				return contentImages.subList(0, 2);
			}else if (contentImages.size() == 2){
				
				return contentImages.subList(0,1);
			} else if (contentImages.size() == 1) {
				String s = contentImages.get(0);
				ArrayList<String> objects = new ArrayList<>();
				objects.add(s);
				return objects;
			} else {
				return new ArrayList<>();
			}
			
		} else {
			return images;
		}
	}
	
	private WmNews wmNewsDot2WmNews(WmNewsDto wmNewsDto) {
		if (wmNewsDto == null) {
			return null;
		}
		WmNews wmNews = new WmNews();
		BeanUtils.copyProperties(wmNewsDto, wmNews);
		
		
		if (wmNewsDto.getType() == -1) {
			wmNews.setType(null);
		}
		
		wmNews.setUserId(WmUserThreadLocal.get().getId());
		wmNews.setCreatedTime(new Date());
		wmNews.setEnable((short)1);
		
		List<String> images = wmNewsDto.getImages();
		if (!CollectionUtils.isEmpty(images)) {
			String join = StringUtils.join(images, ",");
			wmNews.setImages(join);
		}
		return wmNews;
		
	}
	
	private List<String> getContenImages(String content) {
		if (StringUtils.isEmpty(content)) {
			return new ArrayList<>();
		}
		List<String> urlList = new ArrayList<>();
		List<Map> maps = JSON.parseArray(content, Map.class);
		if (CollectionUtils.isEmpty(maps)) {
			return new ArrayList<>();
		}
		
		for (Map map : maps) {
			if (CollectionUtils.isEmpty(map)) {
				continue;
			}
			Object type = map.get("type");
			if ("image".equals(type)) {
				String value = (String)map.get("value");
				urlList.add(value);
			}
		}
		return urlList;
	}
	@Override
	public PageResponseResult getNewsList(WmNewsPageReqDto dto) {
		if (dto == null) {
			
			return new PageResponseResult(0, 0, 0);
		}
		Page<WmNews> wmNewsPage = new Page<>(dto.getPage(), dto.getSize());
		Integer id = WmUserThreadLocal.get().getId();
		
		LambdaQueryWrapper<WmNews> wrapper = new LambdaQueryWrapper<>();
		
		Date beginPubDate = dto.getBeginPubDate();
		Date endPubDate = dto.getEndPubDate();
		
		//组装查询条件
		wrapper.eq(dto.getStatus() != null, WmNews::getStatus, dto.getStatus());
		wrapper.eq(id != null, WmNews::getUserId, id);
		wrapper.between(beginPubDate != null && endPubDate != null, WmNews::getPublishTime, beginPubDate, endPubDate);
		wrapper.eq(dto.getChannelId() != null, WmNews::getChannelId, dto.getChannelId());
		wrapper.like(StringUtils.isNotEmpty(dto.getKeyword()), WmNews::getTitle, dto.getKeyword());
		wrapper.orderByDesc(WmNews::getPublishTime);
		
		Page<WmNews> page = wmNewsMapper.selectPage(wmNewsPage, wrapper);
		
		PageResponseResult pageResponseResult = new PageResponseResult((int)page.getCurrent(), dto.getSize(), (int)page.getTotal());
		pageResponseResult.setData(page.getRecords());
		return pageResponseResult;
	}
}
